package com.wobito.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.wobito.common.properties.OSSProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component
public class AliOSSUtils {

    @Resource
    private OSSProperties ossProperties;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        String dir = "images/";
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        System.err.println(originalFilename);
        String fileName = dir + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret());
        ossClient.putObject(ossProperties.getBucketName(), fileName, inputStream);

        //文件访问路径
        String url = ossProperties.getEndpoint().split("//")[0] + "//" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint().split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    /**
     * 重载upload方法
     * @param file
     * @param filename
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile file, String filename) throws IOException {
        String dir = "images/";
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String fileName = dir + UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret());
        ossClient.putObject(ossProperties.getBucketName(), fileName, inputStream);

        //文件访问路径
        String url = ossProperties.getEndpoint().split("//")[0] + "//" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint().split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    public void delete(String uri) {
        // 创建OSSClient实例（OSS客户端实例）
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        // 判断是否删除成功
        //boolean deleteFileSucceed = false;
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            String file = "images/" + uri;
            ossClient.deleteObject(ossProperties.getBucketName(), file);
            ossClient.shutdown();
            //deleteFileSucceed = true;
            System.out.println("文件" + file + "删除成功");
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}